<template>
  <div class="workorder-list">
    <!-- 搜索和筛选栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="工单类别">
          <el-select
            v-model="searchForm.category"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="案件委托工单" :value="1" />
            <el-option label="法务工单" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择"
            clearable
            style="width: 120px"
          >
            <el-option label="待分配" :value="1" />
            <el-option label="进行中" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已取消" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行人">
          <el-select
            v-model="searchForm.assigneeId"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 标签页 -->
    <el-card shadow="never" class="tab-card">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card">
        <el-tab-pane label="收到的工单" name="received" />
        <el-tab-pane label="已分配的工单" name="assigned" />
        <el-tab-pane label="待分配工单" name="pending" />
      </el-tabs>
    </el-card>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      v-loading="loading"
      stripe
      style="width: 100%"
      @row-click="handleRowClick"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="work_order_no" label="工单编号" min-width="150" />
      <el-table-column prop="order_no" label="关联订单" min-width="150" />
      <el-table-column prop="customer_name" label="客户名称" min-width="150" />
      <el-table-column prop="category" label="工单类别" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.category === 1" type="danger">案件委托工单</el-tag>
          <el-tag v-else type="primary">法务工单</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="工单标题" min-width="200" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="info">待分配</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="warning">进行中</el-tag>
          <el-tag v-else-if="scope.row.status === 3" type="success">已完成</el-tag>
          <el-tag v-else type="danger">已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.priority === 1" type="danger">高</el-tag>
          <el-tag v-else-if="scope.row.priority === 2" type="warning">中</el-tag>
          <el-tag v-else type="info">低</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="assignee_name" label="执行人" width="120" />
      <el-table-column prop="department_manager_name" label="部门经理" width="120" />
      <el-table-column prop="create_time" label="创建时间" width="160">
        <template #default="scope">
          {{ formatDateTime(scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="scope">
          <el-button type="text" @click.stop="handleView(scope.row)">查看</el-button>
          <el-button
            type="text"
            @click.stop="handleAssign(scope.row)"
            v-if="scope.row.status === 1 && isDepartmentManager"
          >
            分配
          </el-button>
          <el-button
            type="text"
            @click.stop="handleAddProgress(scope.row)"
            v-if="canOperate(scope.row)"
          >
            添加进度
          </el-button>
          <el-button
            type="text"
            @click.stop="handleComplete(scope.row)"
            v-if="scope.row.status === 2 && canOperate(scope.row)"
          >
            完成
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 工单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="工单详情" width="900px">
      <div v-if="currentWorkOrder">
        <el-descriptions :column="2" border class="mb-20">
          <el-descriptions-item label="工单编号">
            {{ currentWorkOrder.work_order_no }}
          </el-descriptions-item>
          <el-descriptions-item label="关联订单">
            {{ currentWorkOrder.order_no }}
          </el-descriptions-item>
          <el-descriptions-item label="客户名称">
            {{ currentWorkOrder.customer_name }}
          </el-descriptions-item>
          <el-descriptions-item label="工单类别">
            <el-tag v-if="currentWorkOrder.category === 1" type="danger">案件委托工单</el-tag>
            <el-tag v-else type="primary">法务工单</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag v-if="currentWorkOrder.status === 1" type="info">待分配</el-tag>
            <el-tag v-else-if="currentWorkOrder.status === 2" type="warning">进行中</el-tag>
            <el-tag v-else-if="currentWorkOrder.status === 3" type="success">已完成</el-tag>
            <el-tag v-else type="danger">已取消</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag v-if="currentWorkOrder.priority === 1" type="danger">高</el-tag>
            <el-tag v-else-if="currentWorkOrder.priority === 2" type="warning">中</el-tag>
            <el-tag v-else type="info">低</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="执行人">
            {{ currentWorkOrder.assignee_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="部门经理">
            {{ currentWorkOrder.department_manager_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(currentWorkOrder.create_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">
            {{ currentWorkOrder.start_time ? formatDateTime(currentWorkOrder.start_time) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="预计结束时间">
            {{ currentWorkOrder.end_time ? formatDateTime(currentWorkOrder.end_time) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="实际结束时间" v-if="currentWorkOrder.actual_end_time">
            {{ formatDateTime(currentWorkOrder.actual_end_time) }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="section">
          <h3>工单描述</h3>
          <div class="description">{{ currentWorkOrder.description }}</div>
        </div>

        <div class="section">
          <h3>进度记录</h3>
          <el-timeline>
            <el-timeline-item
              v-for="progress in currentWorkOrder.progress_list"
              :key="progress.id"
              :timestamp="formatDateTime(progress.create_time)"
              placement="top"
            >
              <el-card>
                <div class="progress-item">
                  <div class="progress-header">
                    <span class="progress-operator">{{ progress.operator_name }}</span>
                    <el-tag v-if="progress.progress_type === 1" type="info">状态变更</el-tag>
                    <el-tag v-else type="primary">进度添加</el-tag>
                  </div>
                  <div class="progress-content">{{ progress.content }}</div>
                  <div class="progress-status" v-if="progress.old_status || progress.new_status">
                    <span v-if="progress.old_status">
                      原状态：{{ getStatusText(progress.old_status) }}
                    </span>
                    <span v-if="progress.new_status">
                      → 新状态：{{ getStatusText(progress.new_status) }}
                    </span>
                  </div>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>

    <!-- 分配工单对话框 -->
    <el-dialog v-model="assignDialogVisible" title="分配工单" width="500px">
      <el-form :model="assignForm" label-width="120px">
        <el-form-item label="工单">
          <span>{{ currentWorkOrder?.work_order_no }}</span>
        </el-form-item>
        <el-form-item label="选择执行人" prop="assignee_id">
          <el-select
            v-model="assignForm.assignee_id"
            placeholder="请选择执行人"
            style="width: 100%"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitAssign">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加进度对话框 -->
    <el-dialog v-model="progressDialogVisible" title="添加进度" width="600px">
      <el-form :model="progressForm" label-width="120px">
        <el-form-item label="工单">
          <span>{{ currentWorkOrder?.work_order_no }}</span>
        </el-form-item>
        <el-form-item label="进度内容" prop="content">
          <el-input
            v-model="progressForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入进度内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="progressDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitProgress">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useRouter } from 'vue-router'

  const router = useRouter()

  // 定义接口类型
  interface UserOption {
    id: number
    name: string
  }

  interface WorkOrderProgress {
    id: number
    operator_name: string
    progress_type: number
    content: string
    create_time: number | string
    old_status?: number
    new_status?: number
  }

  interface WorkOrder {
    id: number
    work_order_no: string
    order_no: string
    customer_name: string
    category: number
    title: string
    status: number
    priority: number
    assignee_name?: string
    department_manager_name?: string
    create_time: number | string
    start_time?: number | string
    end_time?: number | string
    actual_end_time?: number | string
    description: string
    progress_list?: WorkOrderProgress[]
  }

  // 当前激活的标签页
  const activeTab = ref('received')

  // 搜索表单
  const searchForm = reactive({
    category: '',
    status: '',
    assigneeId: '',
  })

  // 表格数据
  const tableData = ref<WorkOrder[]>([])
  const loading = ref(false)
  const pagination = reactive({
    page: 1,
    limit: 20,
    total: 0,
  })

  // 选项数据
  const userOptions = ref<UserOption[]>([])

  // 详情对话框
  const detailDialogVisible = ref(false)
  const currentWorkOrder = ref<WorkOrder | null>(null)

  // 分配对话框
  const assignDialogVisible = ref(false)
  const assignForm = reactive({
    assignee_id: '',
  })

  // 进度对话框
  const progressDialogVisible = ref(false)
  const progressForm = reactive({
    content: '',
  })

  // 是否是部门经理（根据实际情况判断）
  const isDepartmentManager = computed(() => {
    // TODO: 从用户信息中获取
    return false
  })

  // 初始化
  onMounted(() => {
    fetchData()
    fetchUserOptions()
  })

  // 获取表格数据
  const fetchData = async () => {
    loading.value = true
    try {
      const { workorderApi } = await import('@/api/workorder')
      const params: any = {
        page: pagination.page,
        limit: pagination.limit,
      }

      // 添加表单搜索条件
      if (searchForm.category) params.category = searchForm.category
      if (searchForm.status) params.status = searchForm.status
      if (searchForm.assigneeId) params.assigneeId = searchForm.assigneeId

      // 添加标签页对应的筛选条件
      const tabFilterParams = getTabFilterParams()
      Object.assign(params, tabFilterParams)

      const res = await workorderApi.getWorkOrderList(params)
      if (res.code === 0) {
        tableData.value = res.data.list || []
        pagination.total = res.data.total || 0
      } else {
        ElMessage.error(res.msg || '获取数据失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取数据失败')
    } finally {
      loading.value = false
    }
  }

  // 获取用户选项
  const fetchUserOptions = async () => {
    try {
      const { workorderApi } = await import('@/api/workorder')
      const res = await workorderApi.getUserOptions()
      if (res.code === 0) {
        userOptions.value = res.data || []
      }
    } catch (error) {
      console.error(error)
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    fetchData()
  }

  // 重置
  const handleReset = () => {
    searchForm.category = ''
    searchForm.status = ''
    searchForm.assigneeId = ''
    handleSearch()
  }

  // 处理标签页切换
  const handleTabClick = () => {
    pagination.page = 1
    fetchData()
  }

  // 根据标签页获取筛选参数
  const getTabFilterParams = () => {
    const filterParams: any = {}

    // 根据不同标签页设置对应的筛选条件
    switch (activeTab.value) {
      case 'pending':
        // 待分配工单：状态为1
        filterParams.status = 1
        break
      case 'received':
        // 收到的工单：不设置特殊筛选，可能需要根据用户身份判断
        // 这里暂时保持原样，可以根据需要调整
        break
      case 'assigned':
        // 已分配的工单：状态为2或3
        // 注意：这里不直接在params中设置多值条件，可能需要在fetchData中处理
        // 或者后端需要支持多值状态查询
        break
    }

    return filterParams
  }

  // 查看详情
  const handleView = async (row: WorkOrder) => {
    detailDialogVisible.value = true
    currentWorkOrder.value = row
    await fetchProgressList(row.id)
  }

  // 分配工单
  const handleAssign = (row: WorkOrder) => {
    currentWorkOrder.value = row
    assignForm.assignee_id = ''
    assignDialogVisible.value = true
  }

  // 添加进度
  const handleAddProgress = (row: WorkOrder) => {
    currentWorkOrder.value = row
    progressForm.content = ''
    progressDialogVisible.value = true
  }

  // 完成工单
  const handleComplete = async (row: WorkOrder) => {
    try {
      await ElMessageBox.confirm('确定要完成此工单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      const { workorderApi } = await import('@/api/workorder')
      const res = await workorderApi.completeWorkOrder(row.id)
      if (res.code === 0) {
        ElMessage.success('工单已完成')
        fetchData()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    } catch (error) {
      console.log('用户取消')
    }
  }

  // 行点击
  const handleRowClick = (row: WorkOrder) => {
    handleView(row)
  }

  // 检查是否可以操作
  const canOperate = (row: WorkOrder) => {
    // TODO: 根据权限判断
    return true
  }

  // 获取进度列表
  const fetchProgressList = async (workOrderId: number) => {
    try {
      const { workorderApi } = await import('@/api/workorder')
      const res = await workorderApi.getWorkOrderProgress(workOrderId)
      if (res.code === 0 && currentWorkOrder.value) {
        currentWorkOrder.value.progress_list = res.data.list || []
      }
    } catch (error) {
      console.error(error)
    }
  }

  // 提交分配
  const handleSubmitAssign = async () => {
    if (!assignForm.assignee_id) {
      ElMessage.warning('请选择执行人')
      return
    }

    if (!currentWorkOrder.value) {
      ElMessage.error('工单信息异常')
      return
    }

    try {
      const { workorderApi } = await import('@/api/workorder')
      const res = await workorderApi.assignWorkOrder(currentWorkOrder.value.id, {
        assignee_id: Number(assignForm.assignee_id),
      })
      if (res.code === 0) {
        ElMessage.success('分配成功')
        assignDialogVisible.value = false
        fetchData()
      } else {
        ElMessage.error(res.msg || '分配失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('分配失败')
    }
  }

  // 提交进度
  const handleSubmitProgress = async () => {
    if (!progressForm.content) {
      ElMessage.warning('请输入进度内容')
      return
    }

    if (!currentWorkOrder.value) {
      ElMessage.error('工单信息异常')
      return
    }

    try {
      const { workorderApi } = await import('@/api/workorder')
      const res = await workorderApi.addProgress(currentWorkOrder.value.id, {
        content: progressForm.content,
      })
      if (res.code === 0) {
        ElMessage.success('添加成功')
        progressDialogVisible.value = false
        if (currentWorkOrder.value) {
          fetchProgressList(currentWorkOrder.value.id)
        }
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('添加失败')
    }
  }

  // 分页
  const handleSizeChange = (val: number) => {
    pagination.limit = val
    fetchData()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    fetchData()
  }

  // 格式化日期
  const formatDateTime = (timestamp: number | string) => {
    if (!timestamp) return ''
    // 确保timestamp是数字类型再乘以1000
    const dateValue = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp
    const date = new Date(dateValue * 1000)
    return date.toLocaleString()
  }

  // 获取状态文本
  const getStatusText = (status: number) => {
    const map: Record<number, string> = {
      1: '待分配',
      2: '进行中',
      3: '已完成',
      4: '已取消',
    }
    return map[status] || '未知'
  }
</script>

<style lang="scss" scoped>
  .workorder-list {
    padding: 20px;

    .search-bar {
      background: #f5f5f5;
      padding: 20px;
      border-radius: 4px;
      margin-bottom: 20px;
    }

    .tab-card {
      margin-bottom: 20px;
    }

    .pagination {
      margin-top: 20px;
      text-align: right;
    }

    .mb-20 {
      margin-bottom: 20px;
    }

    .section {
      margin-top: 20px;

      h3 {
        margin-bottom: 15px;
        font-size: 16px;
        font-weight: bold;
      }
    }

    .description {
      padding: 15px;
      background: #f5f5f5;
      border-radius: 4px;
      line-height: 1.6;
    }

    .progress-item {
      .progress-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;

        .progress-operator {
          font-weight: bold;
        }
      }

      .progress-content {
        margin-bottom: 10px;
        line-height: 1.6;
      }

      .progress-status {
        font-size: 14px;
        color: #666;
      }
    }
  }
</style>
